package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单定时任务处理类
 */
@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时未支付订单
     * 每分钟运行一次
     */
    //@Scheduled(cron = "0/5 * * * * ?")
//    @Scheduled(cron = "10 * * * * ?")
    private void orderTaskCancel(){
        //1.找到未支付订单
        //1.1 根据订单状态以及时间查询
        //加分钟
//        LocalDateTime time = LocalDateTime.now().plususMinutes(-15);
        //当前时间减少15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //调用sql查询
        List<Orders> orderList = orderMapper.selectOrderByStatusAndTime(Orders.PENDING_PAYMENT,time);
        //2.把找到的订单修改为取消
        if (CollectionUtils.isNotEmpty(orderList)){
            for (Orders orders : orderList) {
                Orders ordersUpdate = new Orders();
                //更新的实体类
                ordersUpdate.setId(orders.getId());
                //更新状态 待支付-》已取消
                ordersUpdate.setStatus(orders.CANCELLED);
                //取消原因
                ordersUpdate.setCancelReason("超时未支付付款");
                //取消时间
                ordersUpdate.setCancelTime(LocalDateTime.now());
                //调用更新方法
                orderMapper.update(ordersUpdate);
            }
        }
    }

    /**
     * 处理派送超过一小时未完成订单
     * 凌晨一点执行
     */
//    @Scheduled(cron = "0 0 1 * * ?")
    public void orderTaskDelivery(){
        //根据条件查询出所有符合规则的订单
        //派送中 & 超过当前时间一小时
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        List<Orders> orders = orderMapper.selectOrderByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (CollectionUtils.isNotEmpty(orders)){
            for (Orders order : orders) {
                Orders updateOrder = new Orders();
                updateOrder.setId(order.getId());
                //设置为订单已完成
                updateOrder.setStatus(Orders.COMPLETED);
                orderMapper.update(updateOrder);
            }
        }
    }
}
